package com.ruicar.afs.cloud.apply.contract.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.apply.common.entity.ApplyCarDetails;
import com.ruicar.afs.cloud.apply.common.entity.ApplyContractInfo;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOrderInfo;
import com.ruicar.afs.cloud.apply.common.entity.CarInvoiceConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.condition.ContractCondition;
import com.ruicar.afs.cloud.apply.contract.mapper.ContractMngMapper;
import com.ruicar.afs.cloud.apply.contract.service.CarInvoiceConfigService;
import com.ruicar.afs.cloud.apply.contract.service.ContractMngService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ContractMngCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.OrderOprCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyCarDetailsService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOrderInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.vo.ContractMngLoanAppVO;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyFinancingItemsService;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.security.vo.RoleVo;
import com.ruicar.afs.cloud.parameter.commom.enums.CarNature;
import com.ruicar.afs.cloud.parameter.commom.enums.CostType;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 放款申请-订单管理-接口实现类
 *
 * @author 耿继辉
 */
@Service
@AllArgsConstructor
public class ContractMngServiceImpl implements ContractMngService {

    private final ContractMngMapper contractMngMapper;
    private ApplyCostDetailsService costDetailsService;
    private ApplyFinancingItemsService financingItemsService;
    private CarInvoiceConfigService carInvoiceConfigService;
    private ApplyCarDetailsService applyCarDetailsService;
    private ApplyOrderInfoService applyOrderInfoService;
    /**
     * 多条件查询
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public IPage<ContractMngLoanAppVO> getMngLoanOrderInfo(ContractMngCondition condition, Page page) {
        // 用户名
        condition.setCreateBy(SecurityUtils.getUsername());
        JSONArray jsonArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("deptIds");
        if(jsonArray!=null){
            // 部门列表
            condition.setDeptIds(jsonArray.toJavaList(String.class));
        }
        condition.setDeptId(String.valueOf(SecurityUtils.getUser().getDeptId()));
        JSONArray roleArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("roles");
        if(roleArray != null){
            List<RoleVo> roleList = roleArray.toJavaList(RoleVo.class);
            condition.setRoleList(roleList);
        }
        return this.contractMngMapper.getMngLoanOrderInfo(condition, page);
    }

    /**
     * 获取合同信息
     *
     * @param condition
     * @return
     */
    @Override
    public ApplyContractInfo getContractInfo(OrderOprCondition condition) {
        return this.contractMngMapper.getContractInfo(condition);
    }

    /**
     * 更新客户信息
     *
     * @param contractInfo
     * @return
     */
    @Override
    public Boolean updateContractInfo(ApplyContractInfo contractInfo) {
        return this.contractMngMapper.updateContractInfo(contractInfo);
    }

    /**
     * 获取最低发票金额
     *
     * @return
     */
    @Override
    public BigDecimal getMinInvoiceAmt(String applyNo) {

        BigDecimal minInvoiceAmt = BigDecimal.ZERO;
        BigDecimal loanAmt;
        BigDecimal allMoney= BigDecimal.ZERO;
        BigDecimal allLoanMoney =  BigDecimal.ZERO;
        FinCostDetails costDetails = costDetailsService.getApplyCostDetails(applyNo, CostType.CARAMT.getIndex());
        FinCostDetails costDetails2 = costDetailsService.getApplyCostDetails(applyNo, CostType.AFFIXAMT.getIndex());
        ApplyCarDetails applyCarDetails=applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda()
        .eq(ApplyCarDetails::getApplyNo,applyNo));
        ApplyOrderInfo applyOrderInfo=applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda()
        .eq(ApplyOrderInfo::getApplyNo,applyNo));
        if(!applyOrderInfo.getCarNature().equals(CarNature.NEW_CAR.getIndex())&&!applyOrderInfo.getCarNature().equals(CarNature.PLATE_CAR.getIndex())){
            return new BigDecimal("0");
        }
        String isGreen = "0";
        if(applyCarDetails.getIsGreen()!=null){
            isGreen=applyCarDetails.getIsGreen();
        }
        CarInvoiceConfig carInvoiceConfig=carInvoiceConfigService.getOne(Wrappers.<CarInvoiceConfig>query().lambda()
        .eq(CarInvoiceConfig::getIsGreen,isGreen)
        .eq(CarInvoiceConfig::getCarType,applyOrderInfo.getCarType()));
        //非本品
        BigDecimal max;
        if(applyCarDetails.getBrandName().indexOf(ApplyConstants.IS_GREAT_WALL)<0){
            max=carInvoiceConfig.getMultiBrandScale();
        }else{
          //本品
            max=carInvoiceConfig.getSelfBrandScale();
        }
        if (costDetails != null) {
            if(costDetails.getIsSubProduct()==null || ("").equals(costDetails.getIsSubProduct())){
                if(costDetails2!=null){
                    allMoney=costDetails.getContractAmt().add(costDetails2.getContractAmt());
                    allLoanMoney=costDetails.getLoanAmt().add(costDetails2.getLoanAmt());
                }else{
                    allMoney=costDetails.getContractAmt();
                    allLoanMoney=costDetails.getLoanAmt();
                }
            } else if(costDetails.getIsSubProduct().equals(ApplyConstants.IS_NOT_SUB_PRODUCT)){
                    allMoney=costDetails.getContractAmt().add(costDetails.getAddAmt()==null?BigDecimal.ZERO:costDetails.getAddAmt());
                    allLoanMoney=costDetails.getLoanAmt();
            }else if(costDetails.getIsSubProduct().equals(ApplyConstants.IS_SUB_PRODUCT)){
                if(costDetails2!=null){
                    allMoney=costDetails.getContractAmt().add(costDetails2.getContractAmt());
                    allLoanMoney=costDetails.getLoanAmt().add(costDetails2.getLoanAmt());
                }else{
                    allMoney=costDetails.getContractAmt();
                    allLoanMoney=costDetails.getLoanAmt();
                }
            }
            BigDecimal contractAmt = costDetails.getContractAmt();
            loanAmt=((contractAmt.multiply((allLoanMoney.divide(allMoney,10,BigDecimal.ROUND_HALF_DOWN)))).divide(new BigDecimal(String.valueOf(max)),10,BigDecimal.ROUND_HALF_DOWN));
            // 车辆贷款金额/车辆最高贷款比例
            if (minInvoiceAmt.compareTo(loanAmt) < 0) {
                minInvoiceAmt = loanAmt.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            }
            // 车辆价格*0.95
            if (minInvoiceAmt.compareTo(contractAmt.multiply(new BigDecimal("0.95"))) < 0) {
                minInvoiceAmt = contractAmt.multiply(new BigDecimal("0.95"));
            }
        }
        // 购置税加金融金额*1.13/10%
        FinFinancingItems finFinancingItems =financingItemsService.getApplyFinancingItems(applyNo, ApplyConstants.PURCHASE_TAX);
        if(finFinancingItems != null){
            if(minInvoiceAmt.compareTo(finFinancingItems.getFinanceItemAmt().multiply(new BigDecimal("1.13").divide(new BigDecimal("0.1"),2,BigDecimal.ROUND_HALF_DOWN)))<0){
                minInvoiceAmt = finFinancingItems.getFinanceItemAmt().multiply(new BigDecimal("1.13").divide(new BigDecimal("0.1"),2,BigDecimal.ROUND_HALF_DOWN));
            }
        }
        return minInvoiceAmt;
    }

    public IPage<List<ApplyContractInfo>> getGpsAgainInfo(ContractCondition condition, Page page) {
        return this.contractMngMapper.getGpsAgainInfo(condition, page);
    }
}
